package com.hmall.order.listener;

import com.hmall.common.clients.ItemClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.constants.OrderStatusConstants;
import com.hmall.common.response.ItemUpdateStockVO;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Component
@Slf4j
public class SpringRabbitListener {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private ItemClient itemClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE, delayed = "true"),
            key = MqConstants.DELAY_KEY
    ))
    public void listenDelayedQueue(String msg) {
        log.info("接收到delay.queue的延迟消息：{}", msg);
        Long orderId = Long.valueOf(msg);
        // 1-根据订单id查询订单
        Order order = orderMapper.selectById(orderId);

        // 订单合法性判断
        if (Objects.isNull(order)) {
            return;
        }
        // 2-判断订单status是否为1
        if (!Objects.equals(1, order.getStatus())) {
            return;
        }
        // 3-幂等判断
        if (Objects.nonNull(order.getCloseTime())){
            return;
        }
        // 4-根据订单id查询订单详情，得到商品购买数量
        OrderDetail orderDetail = orderDetailMapper.selectByOrderId(orderId);
        Integer num = orderDetail.getNum();
        Long itemId = orderDetail.getItemId();
        // 5-根据订单id修改订单status为5
        Order updateOrder=new Order();
        updateOrder.setId(orderId);
        updateOrder.setCloseTime(new Date());
        updateOrder.setStatus(OrderStatusConstants.CANCEL);
        orderMapper.updateById(updateOrder);
        // 6-调用item-service，根据商品id、商品数量恢复库存
        ItemUpdateStockVO result = itemClient.addStock(itemId, num);
        log.info("更新结果：{}",result);
    }
}
